package com.tiocloud.chat.mvp.launcher;

import android.os.Handler;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.tiocloud.chat.widget.dialog.tio.ProtectGuideDialog;
import com.watayouxiang.androidutils.mvp.BaseModel;
import com.watayouxiang.androidutils.widget.TioToast;

/**
 * author : TaoWang
 * date : 2020-02-12
 * desc : 应用启动表现层
 */
public class LauncherPresenter extends LauncherContract.Presenter {

    public LauncherPresenter(LauncherContract.View view) {
        super(view);
    }

    @Override
    public void init() {
        // 显示隐私政策确认弹窗
        new ProtectGuideDialog(getView().getActivity(), this::reqPermission).checkConfirm();
    }

    private void reqPermission() {
        PermissionUtils.permission(PermissionConstants.PHONE, PermissionConstants.LOCATION)
                .rationale((activity, shouldRequest) -> shouldRequest.again(true))
                .callback((isAllGranted, granted, deniedForever, denied) -> reqConfig())
                .request();
    }

    private void reqConfig() {
        getModel().requestConfig(new BaseModel.DataProxy<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                openNextPage();
            }

            @Override
            public void onFailure(String msg) {
                super.onFailure(msg);
                exitApp("获取配置信息失败：" + msg);
            }
        });
    }

    private void openNextPage() {
        if (!getModel().isLogin()) {
            getView().openLoginPage();
        } else {
            getView().openMainPage();
        }
        getView().finish();
    }

    private void exitApp(String reason) {
        TioToast.showShort(reason);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AppUtils.exitApp();
            }
        }, 2000);
    }
}
